<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed!');

class User_model extends OC_Model {

	function get_users($params = array())
	{
		$this->db->select('SQL_CALC_FOUND_ROWS a.*, b.*, d.name group_name', FALSE);
		$this->db->from('o_users a');
		$this->db->join('o_userdata b', 'a.user_id = b.user_id');
		$this->db->join('o_assoc c', 'a.user_id = c.user_id');
		$this->db->join('o_groups d', 'c.group_id = d.group_id');

		if (isset($params['sort'], $params['order']))
			$this->db->order_by($params['sort'], $params['order']);

		if (isset($params['page'], $params['rows']))
			$this->db->limit($params['rows'], (intval($params['page']-1)*intval($params['rows'])));

		if (isset($params['query']) && $params['query'] != '')
		{
			$query = $params['query'];

			$likes = array_map(
				function($f) use ($query) { return "$f LIKE '%$query%'"; }, 
				array('a.username', 'b.fullname', 'b.email', 'd.name')
			);
			
			$this->db->where('('.implode(' OR ', $likes).')');
		}
		
		return $this->fetch_rows();
	}

	function delete_user($user_id)
	{
		$keys = array('user_id' => $user_id);
		// delete from assoc
		$this->db->delete('o_assoc', $keys);
		// delete from data
		$this->db->delete('o_userdata', $keys);
		// delete from master
		return $this->db->delete('o_users', $keys);
	}

	function get_groups()
	{
		$this->db->from('o_groups');
		return $this->fetch_rows();
	}

	function get_assoc()
	{
		$this->db->select('a.group_id, a.user_id, b.name group_name, c.username, d.fullname');
		$this->db->from('o_assoc a');
		$this->db->join('o_groups b', 'a.group_id = b.group_id');
		$this->db->join('o_users c', 'a.user_id = c.user_id');
		$this->db->join('o_userdata d', 'c.user_id = d.user_id');
		return $this->fetch_rows();
	}

}